const { courseModel, workTeaModel, chapter_opened, classModel, stuModel, openedModel } = require('../../model');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const { getResultToObjectComplete, getResultToObject } = require('../../services/utils');

module.exports = {
  listByChapter: function (req,res) {
    const { org, account } = req.decode;
    const { chapter } = req.query;
    const work_attr = ['fileURL', 'pageURL'];
    const cour_attr = ['id', 'order', 'name', 'description', 'work_id', 'type'];
    const cour_where = { org: org, chapter: parseInt(chapter)};
    courseModel.findByRelation(cour_attr, cour_where,{
      model: workTeaModel.getModel(),
      attributes: work_attr
    }).then(result => {
      const list = getResultToObjectComplete(result, 'works_teach', work_attr);
      res.send({
        code: 20000,
        data: {
          items: list,
          total: list.length
        }
      });
    }).catch(err => {
      console.log(err);
      res.send({
        code: 10000,
        message: '获取关卡失败'
      });
    })
  },
  create: async (req,res) => {
    let Type;
    const org = req.decode.org;
    const { chapter, description, name, work_id, type } = req.body;
    if (typeof(type) === 'string') {
      Type = parseInt(type)
    }
    try {
      const course = await courseModel.findByFilter(['id'], {org: org, chapter: chapter});
      const total = course.length;
      const config = {
        order: total + 1,
        org: org,
        chapter: chapter,
        name: name,
        description: description,
        work_id: work_id,
        type: Type,
        updatedAt: Date.now(),
        createdAt: Date.now()
      };
      await courseModel.create(config);
      return res.send({
        code: 20000
      })
    } catch (e) {
      console.log(e)
    }
  },
  delete: function (req,res) {
    const org = req.decode.org;
    const { id, order, chapter } = req.body;

    courseModel.delete({id: id, org: org}).then(() => {
      courseModel.decrement('order',{
        chapter: chapter,
        org: org,
        order:{
          [Op.gt]: order
        }
      }).then(() => {
        return res.send({
          code: 20000,
          message: '关卡删除成功'
        });
      })
    }).catch(err => {
      console.log(err);
      return res.send({
        code: 10000,
        message: '关卡删除失败'
      });
    });
  },
  update: function (req,res) {
    const org = req.decode.org;
    const { id, name, description, work_id, type } = req.body;
    const attributes = { name: name, description: description, work_id: work_id, type: type };
    const where = { id: id, org: org };
    courseModel.update(attributes,where).then(function () {
      res.send({
        code: 20000
      })
    }).catch(function (err) {
      console.log(err);
      res.send({
        code: 10000
      })
    })
  },
  order: async (req,res) => {
    const { org } = req.decode;
    const { current, target, curOrder, tarOrder } = req.body;

    try {
      await courseModel.update({ order: curOrder }, { id: current, org: org });
      await courseModel.update({ order: tarOrder }, { id: target, org: org });
      return res.send({
        code: 20000
      })
    } catch (e) {
      console.log(e)
    }
  },
  open: async (req,res) => {
    const { classID, chapterID, courses } = req.body;
    const courseOpenList = [];
    const chapterOpenList = [];
    const time = Date.now();

    try {
      const result = await classModel.findByRelation(['id'], { id: classID, org: req.decode.org },
        { model: stuModel.getModel(), attributes: ['id'] });
      const students = getResultToObject(result, 'students', ['id']);
      if (!students) {
        return res.send({
          code: 20000
        })
      }
      for (const stu of students) {
        for (const item of courses) {
          const openObj = {stu_id: stu.id, course_id: item.id, work_id: item.work_id, createdAt: time, updatedAt: time};
          const chapterOpenObj = {stu_id: stu.id, chapter_id: chapterID, learn_state: 1};
          courseOpenList.push(openObj);
          chapterOpenList.push(chapterOpenObj);
        }
      }
      await chapter_opened.createBatch(chapterOpenList,{ updateOnDuplicate: ['stu_id', 'chapter_id']});
      await openedModel.createBatch(courseOpenList,{ updateOnDuplicate: ['stu_id', 'work_id']});
      return res.send({
        code: 20000
      })
    } catch (e) {
      console.log(e);
      return res.send({code: 10000})
    }
  }
};
